/*
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2025-02-05 15:07:19
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-02-05 15:07:33
 * @FilePath: \asset-management-webc:\Users\21776\Desktop\毕设\shop_app_vue3\store\cartStore.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
//购物车数据
import { defineStore } from 'pinia';
import {
  addToCart,
  updateCart,
  deleteCart,
  clearCart,
  getCartList,
  updateCartSelected,
  selectAllCart,
  getCartCount,
  getCartTotalAmount
} from '../api/cart.js';

export const useCartStore = defineStore('cart', {
  state: () => ({
    // 购物车列表
    cartList: [],
    // 购物车商品总数
    totalCount: 0,
    // 购物车总金额
    totalAmount: 0,
    // 是否全选
    isAllSelected: false
  }),

  getters: {
    // 获取购物车列表
    getCartList: (state) => state.cartList,
    // 获取购物车商品总数
    getCartCount: (state) => state.totalCount,
    // 获取购物车总金额
    getTotalAmount: (state) => state.totalAmount,
    // 获取选中的商品列表
    getSelectedItems: (state) => state.cartList.filter(item => item.selected === 1),
    // 获取选中的商品数量
    getSelectedCount: (state) => state.cartList.filter(item => item.selected === 1).length,
    // 获取选中的商品总金额
    getSelectedAmount: (state) => {
      return state.cartList
        .filter(item => item.selected === 1)
        .reduce((total, item) => total + item.price * item.quantity, 0);
    }
  },

  actions: {
    // 加载购物车列表
    async loadCartList() {
      try {
        const res = await getCartList();
        if (res.code === 200) {
          this.cartList = res.data;
          this.updateSelectStatus();
        }
        return res;
      } catch (error) {
        console.error('加载购物车列表失败:', error);
        throw error;
      }
    },

    // 添加商品到购物车
    async addItemToCart(cartDTO) {
      try {
        const res = await addToCart(cartDTO);
        if (res.code === 200) {
          await this.loadCartList();
          await this.updateCartInfo();
        }
        return res;
      } catch (error) {
        console.error('添加购物车失败:', error);
        throw error;
      }
    },

    // 更新购物车商品
    async updateCartItem(id, cartDTO) {
      try {
        console.log('updateCartItem 被调用，ID:', id, '数据:', cartDTO);
        
        // 首先查找对应购物车项
        const cartItem = this.cartList.find(item => item.id === Number(id));
        if (!cartItem) {
          console.error('找不到购物车项:', id);
          return { code: 500, msg: '找不到购物车项' };
        }
        
        // 删除当前购物车项
        const deleteRes = await deleteCart(Number(id));
        
        if (deleteRes.code === 200) {
          // 添加新的购物车项
          const newCartDTO = {
            fruitId: cartItem.fruitId,
            quantity: cartDTO.quantity,
            selected: cartDTO.selected
          };
          
          console.log('添加新购物车项:', newCartDTO);
          const addRes = await addToCart(newCartDTO);
          
          if (addRes.code === 200) {
            await this.loadCartList();
            await this.updateCartInfo();
          }
          
          return addRes;
        }
        
        return deleteRes;
      } catch (error) {
        console.error('更新购物车失败:', error);
        throw error;
      }
    },

    // 删除购物车商品
    async deleteCartItem(id) {
      try {
        // 确保ID是数字类型
        const cartId = Number(id);
        console.log('deleteCartItem 被调用，转换后的ID:', cartId, '类型:', typeof cartId);
        const res = await deleteCart(cartId);
        if (res.code === 200) {
          await this.loadCartList();
          await this.updateCartInfo();
        }
        return res;
      } catch (error) {
        console.error('删除购物车商品失败:', error);
        throw error;
      }
    },

    // 清空购物车
    async clearCartItems() {
      try {
        const res = await clearCart();
        if (res.code === 200) {
          this.cartList = [];
          this.totalCount = 0;
          this.totalAmount = 0;
          this.isAllSelected = false;
        }
        return res;
      } catch (error) {
        console.error('清空购物车失败:', error);
        throw error;
      }
    },

    // 更新商品选中状态
    async updateItemSelected(id, selected) {
      try {
        // 确保selected是整数
        const selectedValue = Number(selected);
        console.log('updateItemSelected 被调用，ID:', id, '选中状态:', selectedValue, '类型:', typeof selectedValue);
        
        const res = await updateCartSelected(id, selectedValue);
        if (res.code === 200) {
          await this.loadCartList();
          await this.updateCartInfo();
        }
        return res;
      } catch (error) {
        console.error('更新商品选中状态失败:', error);
        throw error;
      }
    },

    // 全选/取消全选
    async toggleSelectAll(selected) {
      try {
        // 确保selected是整数
        const selectedValue = Number(selected);
        console.log('toggleSelectAll 被调用，选中状态:', selectedValue, '类型:', typeof selectedValue);
        
        const res = await selectAllCart(selectedValue);
        if (res.code === 200) {
          await this.loadCartList();
          await this.updateCartInfo();
        }
        return res;
      } catch (error) {
        console.error('全选/取消全选失败:', error);
        throw error;
      }
    },

    // 更新购物车数量和金额信息
    async updateCartInfo() {
      try {
        const [countRes, amountRes] = await Promise.all([
          getCartCount(),
          getCartTotalAmount()
        ]);
        
        if (countRes.code === 200) {
          this.totalCount = countRes.data;
        }
        
        if (amountRes.code === 200) {
          this.totalAmount = amountRes.data;
        }
      } catch (error) {
        console.error('更新购物车信息失败:', error);
        throw error;
      }
    },

    // 更新全选状态
    updateSelectStatus() {
      this.isAllSelected = this.cartList.length > 0 && 
        this.cartList.every(item => item.selected === 1);
    }
  }
});